#pragma execution_character_set("utf-8")
#include "mainquo.h"
#include <QDebug>
#include <QDateTime>
#include "Net/authentication.h"

#include "Main/global.h"
#include "Main/constant_ui.h"


MainQuo::MainQuo()
    :m_pTreeMenu(nullptr)
    ,m_pRiskWatchGrid(nullptr)
{
}

MainQuo::~MainQuo()
{

}

int MainQuo::doLogin( QString qsName, QString qsPwd )
{
    qDebug()<<"doLogin:"<<qsName<<" "<<qsPwd;
    Global::Instance()->Init();
    sprintf(Global::Instance()->gReqHead.user_id,"%s",qsName.toLatin1());

    Authentication au;
    if (au.Login(qsName, qsPwd, m_qsPopMsg))
    {

        m_tradeServer.InitServerAddr(Global::Instance()->GetServerList());
        if (m_tradeServer.Login(qsName, qsPwd, m_qsPopMsg))
        {
            m_riskServer.InitServerAddr(Global::Instance()->GetServerList());

            ShowMainWnd();
            return 0;
        }
    }

    return -1;
}

QString MainQuo::getPopMsg()
{
    return m_qsPopMsg;
}

TreeModel *MainQuo::getTreeMenu()
{
    if (nullptr == m_pTreeMenu)
    {
        m_pTreeMenu = new TreeModel;
        m_pTreeMenu->SetRole(Qt::UserRole+1,"nodeText");

        InitTreeMenu();
    }

    return m_pTreeMenu;
}

TreeModel *MainQuo::getBranchStat()
{
    qDebug()<<"getBranchStat Model";
    return m_pRiskWatchGrid;
}

void MainQuo::openMenu(const QModelIndex &index)
{
    QObject* root = m_pEngine->rootObjects().at(1);
    QString str = m_pTreeMenu->GetNodeText(index).toString();
    if (str.compare(MENUTEXT_RiskWatch) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_RiskWatch;
        ArrayListMsg alm;
        sprintf(Global::Instance()->gReqHead.branch_id,"%s", Global::Instance()->GetParaFrom8001("branch_id").toStdString().c_str());
        m_riskServer.BranchRiskStatQry(Global::Instance()->GetParaFrom8001("branch_id"), alm, m_qsPopMsg);
        InitRiskWatch(alm);

//        QMetaObject::invokeMethod(root, "openRiskWatch",Q_ARG(QVariant, MENUTEXT_RiskWatch));
        QMetaObject::invokeMethod(root, "openTabPage",Q_ARG(QVariant, MENUTEXT_RiskWatch),Q_ARG(QVariant, "RiskWatch.qml"));
    }
    else if (str.compare(MENUTEXT_RiskCalc) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_RiskCalc;
        QMetaObject::invokeMethod(root, "openTabPage",Q_ARG(QVariant, MENUTEXT_RiskCalc),Q_ARG(QVariant, "TryCalcRisk.qml"));
    }
    else if (str.compare(MENUTEXT_SingleForce) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_SingleForce;
        QMetaObject::invokeMethod(root, "openSingleForce",Q_ARG(QVariant, MENUTEXT_SingleForce),Q_ARG(QVariant, ""));
    }
    else if (str.compare(MENUTEXT_BatchForce) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_BatchForce;
        QMetaObject::invokeMethod(root, "openBatchForce",Q_ARG(QVariant, MENUTEXT_BatchForce),Q_ARG(QVariant, Global::Instance()->GetParaFrom8001("branch_id")));
    }
    else if (str.compare(MENUTEXT_ForceManage) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_ForceManage;
        QMetaObject::invokeMethod(root, "openTabPage",Q_ARG(QVariant, MENUTEXT_ForceManage),Q_ARG(QVariant, "ForceOrderQuery.qml"));
    }
    else if (str.compare(MENUTEXT_DegreeDiagram) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_DegreeDiagram;
        QMetaObject::invokeMethod(root, "openTabPage",Q_ARG(QVariant, MENUTEXT_DegreeDiagram),Q_ARG(QVariant, "RiskDistribution.qml"));
    }
    else if (str.compare(MENUTEXT_BranchDiagram) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_BranchDiagram;
        QMetaObject::invokeMethod(root, "openTabPage",Q_ARG(QVariant, MENUTEXT_BranchDiagram),Q_ARG(QVariant, "BranchRiskDistribution.qml"));
    }
    else if (str.compare(MENUTEXT_HisDetail) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_HisDetail;
        QMetaObject::invokeMethod(root, "openTabPage",Q_ARG(QVariant, MENUTEXT_HisDetail),Q_ARG(QVariant, "HisRiskCustList.qml"));
    }
    else if (str.compare(MENUTEXT_QueryRisk) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_QueryRisk;
        QMetaObject::invokeMethod(root, "openTabPage",Q_ARG(QVariant, MENUTEXT_QueryRisk),Q_ARG(QVariant, "RiskCustStatics.qml"));
    }
    else if (str.compare(MENUTEXT_QueryTip) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_QueryTip;
        QMetaObject::invokeMethod(root, "openTabPage",Q_ARG(QVariant, MENUTEXT_QueryTip),Q_ARG(QVariant, "RiskTip.qml"));
    }
    else if (str.compare(MENUTEXT_GradeSet) == 0)
    {
        qDebug()<<"do "<<MENUTEXT_GradeSet;
        QMetaObject::invokeMethod(root, "openTabPage",Q_ARG(QVariant, MENUTEXT_GradeSet),Q_ARG(QVariant, "RiskDegreeSub.qml"));
    }
}

void MainQuo::SetEngine(QQmlApplicationEngine *pEngine, QtQuickControlsApplication* pApp)
{
    m_pEngine = pEngine;
    m_pApp = pApp;
}

void MainQuo::ShowLogin()
{
    m_pEngine->load(QUrl(QStringLiteral("qrc:/Res/qml/login.qml")));
    m_pApp->exec();
}

void MainQuo::ShowMainWnd()
{
    m_pEngine->load(QUrl(QStringLiteral("qrc:/Res/qml/main.qml")));
    if (m_pEngine->rootObjects().isEmpty())
        return ;

    m_pApp->exec();
}

void MainQuo::logout()
{
    ShowLogin();
}

void MainQuo::savePassword(bool bSave)
{
//    QSettings set(QDir::currentPath()+)
}

bool MainQuo::checkPassword(QString pwd)
{
    return pwd.compare(Global::Instance()->m_qsLockKey) == 0;
}

bool MainQuo::dbClickBranchStat(const QModelIndex &index)
{
    ArrayListMsg alm;
//    sprintf(Global::Instance()->gReqHead.branch_id,"%s", m_pRiskWatchGrid->GetNodeText(index).toString().toStdString().c_str());

    m_riskServer.BranchRiskStatQry(m_pRiskWatchGrid->GetNodeText(index).toString(), alm, m_qsPopMsg);
    TreeItem *pRow0 = static_cast<TreeItem*>(index.internalPointer());
    qDebug()<<"pRow0;"<<pRow0->parent()->childCount()<<" dbClick:"<< alm.size();
    if (0 == m_riskServer.GetRiskWatchMode())
    {
        //插入子节点
        for (int i = 1; i < alm.size(); ++i)
        {
            TreeItem* pRow1 = new TreeItem(GetBranchRecord(alm.GetValue(i)), pRow0);
            pRow0->appendChild(pRow1);
        }
    }
    else
    {
        //更新
        for (int i = 1; i < alm.size(); ++i)
        {
            TreeItem* pRow1 = new TreeItem(GetBranchRecord(alm.GetValue(i)), pRow0->parent());
            pRow0->parent()->updateChild(0,pRow1);
            delete pRow1;
        }
    }

    qDebug()<<"after pRow0;"<<pRow0->parent()->childCount();
//    m_pRiskWatchGrid->endResetModel();
    return alm.size() > 1;
}

CColumnConfig* MainQuo::GetColumnConfig()
{
    return &m_colCfg;
}

FileConfig *MainQuo::GetFileConfig()
{
    return &m_config;
}

QString MainQuo::getTradeTime()
{
    return Global::Instance()->GetTradeTime();
}

RspInterface* MainQuo::getCustDetail(const QString acctNo)
{
    RspInterface * pRsp = new RspInterface;
    if (acctNo.trimmed().length() > 0)
        m_riskServer.CustDetailQry(acctNo, pRsp, m_qsPopMsg);

    return pRsp;
}

RspInterface* MainQuo::sendForceOrder(const QString acctNo,const QString orderInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_riskServer.SendForceOrder(acctNo, orderInfo, pRsp);
    return pRsp;
}

QString MainQuo::cancelForceOrder(const QString qsOrderNo)
{
    QString msg;
    m_riskServer.CancelForceOrder(qsOrderNo, msg);
    return msg;
}

RspInterface *MainQuo::tryCalcRiskInfo(const QString acctNo, const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
//    QString req = reqInfo;
//    req.replace("|", ApConst::SEPARATOR_RECORD[1]);
//    req.replace(",", ApConst::SEPARATOR_RECORD[0]);

    m_riskServer.TryCalcRiskInfo(acctNo, reqInfo, pRsp);
    return pRsp;
}

RspInterface *MainQuo::queryPartMatchCovOrder(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_riskServer.QueryPartMatchCovOrder(reqInfo, pRsp);
    return pRsp;
}

RspInterface *MainQuo::queryProdPrice(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_riskServer.QueryProdPrice(reqInfo, pRsp);
    return pRsp;
}

RspInterface * MainQuo::riskTestCalc(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
//    AlmListModel *pModel = new AlmListModel;
    m_riskServer.RiskTestCalc(reqInfo, pRsp, m_qsPopMsg);

//    pModel->InitRoleNames("RiskTryCalc");
//    pModel->InitAlmData(pRsp->m_alms["cal_result"]);
//    qDebug()<<"cal_result size:"<<pRsp->m_alms["cal_result"].size();
//    delete pRsp;
//    return pModel;
    return pRsp;
}

ComboData* MainQuo::getMyBranchs()
{
    return m_tradeServer.GetMyBranchs();
}

AlmListModel *MainQuo::getForceCustModel(int nTop,const QString qsCondition)
{
    AlmListModel* pModel = new AlmListModel;
    pModel->InitRoleNames("RiskCust");

    ArrayListMsg alm3,alm4;
    qDebug()<<"qsCondition:"<<qsCondition;
    QString errMsg;
    QString qsCond3 = qsCondition + "#top_number="+QString::number(nTop);
    m_riskServer.RiskCustListQry(qsCond3+"#risk_grade=3", alm3, errMsg);
    if (alm3.size() < nTop)
    {
        QString qsCond4 = qsCondition + "#top_number="+QString::number(nTop-alm3.size());
        m_riskServer.RiskCustListQry(qsCond4+"#risk_grade=4", alm4, errMsg);
        for (int i = 0; i < alm4.size(); i++)
        {
            ArrayListMsg almTmp = alm4.GetValue(i);
            alm3.AddValue(almTmp);
        }
    }

    pModel->InitAlmData(alm3);
    pModel->setShowCheck(true,true);
    return pModel;
}

QStringList MainQuo::getSomeProdCode(const QStringList qsMarketList2)
{
//    QStringList qsMarketList;//const QList<QString> qsMarketList
    qDebug()<<"getSomeProdCode "<<qsMarketList2;
    return m_tradeServer.GetSomeProdCode(qsMarketList2);
}

ComboData *MainQuo::getCustGradeByBranchs(const QString qsBranchId,bool bAll)
{
    return m_tradeServer.GetCustGradeByBranchs(qsBranchId,bAll);
}

RspInterface *MainQuo::queryForceOrder(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_tradeServer.QueryForceOrder(m_qsPopMsg, pRsp, reqInfo);

    return pRsp;
}

RspInterface *MainQuo::queryRiskCustCount(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_tradeServer.QueryRiskCustCount(m_qsPopMsg, pRsp, reqInfo);

    return pRsp;
}

RspInterface *MainQuo::queryAgentRiskCustCount(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_tradeServer.QueryAgentRiskCustCount(m_qsPopMsg, pRsp, reqInfo);

    return pRsp;
}

RspInterface *MainQuo::queryRiskCustStatics(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_riskServer.QueryRiskCustStatics(reqInfo, pRsp, m_qsPopMsg);

    return pRsp;
}

RspInterface *MainQuo::queryHisRiskCustList(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_tradeServer.QueryHisRiskCustList(m_qsPopMsg, pRsp, reqInfo);

    return pRsp;
}

RspInterface *MainQuo::queryRiskTip(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_riskServer.QueryRiskTip(reqInfo, pRsp, m_qsPopMsg);

    return pRsp;
}

RspInterface *MainQuo::operRiskDegree(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_riskServer.OperRiskDegree(reqInfo, pRsp, m_qsPopMsg);

    return pRsp;
}

QString MainQuo::getCustGradeName(const QString qsID)
{
    return m_tradeServer.GetCustGradeName(qsID);
}

QString MainQuo::getBranchName(const QString qsID)
{
    return m_tradeServer.GetBranchName(qsID);
}

QString MainQuo::getBranchID(const QString qsName)
{
    return m_tradeServer.GetBranchID(qsName);
}

RspInterface *MainQuo::createBatchForceOrder(const QString reqInfo)
{
    RspInterface * pRsp = new RspInterface;
    m_riskServer.CreateBatchForceOrder(reqInfo, pRsp, m_qsPopMsg);

    return pRsp;
}

QStringList MainQuo::getTypeTest()
{
    QStringList l;
    l.append("1");
    l.append("2");
    return l;
}

bool MainQuo::openRiskCustList(const QModelIndex &index)
{
    qDebug()<<"openRiskCustList:"<<m_pRiskWatchGrid->GetNodeText(index).toString();
    QObject* root = m_pEngine->rootObjects().at(1);
    QMetaObject::invokeMethod(root, "openRiskCustList",Q_ARG(QVariant, MENUTEXT_RiskCust),Q_ARG(QVariant, m_pRiskWatchGrid->GetNodeText(index).toString()));
    return true;
}

AlmListModel *MainQuo::getRiskCustModel(const QString tabName, const QString qsCondition)
{
    AlmListModel* pModel = new AlmListModel;
    pModel->InitRoleNames("RiskCust");
    ArrayListMsg alm;
    qDebug()<<"qsCondition:"<<qsCondition;
    m_riskServer.RiskCustListQry(qsCondition, alm, m_qsPopMsg);
    pModel->InitAlmData(alm);
    return pModel;
}

void MainQuo::InitTreeMenu()
{
    QList<QVariant> lV;
    lV.append("风险控制");
    TreeItem* pRiskCtrl = new TreeItem(lV, nullptr);
    qDebug()<<"风险控制:"<<pRiskCtrl;

    QList<QVariant> lV2;
    lV2.append(MENUTEXT_RiskWatch);
    TreeItem* pRiskWatch = new TreeItem(lV2, pRiskCtrl);
    pRiskCtrl->appendChild(pRiskWatch);
    qDebug()<<"风险监控:"<<pRiskWatch;

    QList<QVariant> lV3;
    lV3.append(MENUTEXT_RiskCalc);
    TreeItem* pRiskCalc = new TreeItem(lV3, pRiskCtrl);
    pRiskCtrl->appendChild(pRiskCalc);
    qDebug()<<"风险试算:"<<pRiskCalc;
    m_pTreeMenu->AppendTreeData(pRiskCtrl);

    QList<QVariant> lV1;
    lV1.append("强平管理");
    TreeItem* pForceCtrl = new TreeItem(lV1, nullptr);

    QList<QVariant> lV12;
    lV12.append(MENUTEXT_SingleForce);
    TreeItem* pSingle = new TreeItem(lV12, pForceCtrl);
    pForceCtrl->appendChild(pSingle);

    QList<QVariant> lV13;
    lV13.append(MENUTEXT_BatchForce);
    TreeItem* pBatch = new TreeItem(lV13, pForceCtrl);
    pForceCtrl->appendChild(pBatch);

    QList<QVariant> lV14;
    lV14.append(MENUTEXT_ForceManage);
    TreeItem* pOrder = new TreeItem(lV14, pForceCtrl);
    pForceCtrl->appendChild(pOrder);

//    QList<QVariant> lV15;
//    lV15.append(MENUTEXT_ForcePrint);
//    TreeItem* pPrint = new TreeItem(lV15, pForceCtrl);
//    pForceCtrl->appendChild(pPrint);
    m_pTreeMenu->AppendTreeData(pForceCtrl);

    QList<QVariant> lV22;
    lV22.append("风险监控结果查询");
    TreeItem* pQuery= new TreeItem(lV22, nullptr);

    QList<QVariant> lVV1;
    lVV1.append(MENUTEXT_DegreeDiagram);
    TreeItem* pDegreeD = new TreeItem(lVV1, pQuery);
    pQuery->appendChild(pDegreeD);

    QList<QVariant> lVV2;
    lVV2.append(MENUTEXT_BranchDiagram);
    TreeItem* pBranchD = new TreeItem(lVV2, pQuery);
    pQuery->appendChild(pBranchD);

    QList<QVariant> lVV3;
    lVV3.append(MENUTEXT_HisDetail);
    TreeItem* pHis = new TreeItem(lVV3, pQuery);
    pQuery->appendChild(pHis);

    QList<QVariant> lVV4;
    lVV4.append(MENUTEXT_QueryRisk);
    TreeItem* pQueryRisk = new TreeItem(lVV4, pQuery);
    pQuery->appendChild(pQueryRisk);

    QList<QVariant> lVV5;
    lVV5.append(MENUTEXT_QueryTip);
    TreeItem* pTip = new TreeItem(lVV5, pQuery);
    pQuery->appendChild(pTip);
    m_pTreeMenu->AppendTreeData(pQuery);

    QList<QVariant> lV1V;
    lV1V.append("风险参数");
    TreeItem* pPara = new TreeItem(lV1V, nullptr);

    QList<QVariant> lV1V2;
    lV1V2.append(MENUTEXT_GradeSet);
    TreeItem* pGrade = new TreeItem(lV1V2, pPara);
    pPara->appendChild(pGrade);

//    QList<QVariant> lV1V3;
//    lV1V3.append(MENUTEXT_ParamSet);
//    TreeItem* pParam = new TreeItem(lV1V3, pPara);
//    pPara->appendChild(pParam);
    m_pTreeMenu->AppendTreeData(pPara);
}

void MainQuo::InitRiskWatch(const ArrayListMsg alm)
{
//    if (m_pRiskWatchGrid)
//    {
//        delete m_pRiskWatchGrid;
//        m_pRiskWatchGrid = nullptr;
//    }
//    if (nullptr == m_pRiskWatchGrid)
    {
        m_pRiskWatchGrid = new TreeModel;
        InitRiskWatchRoles();
    }

    int nRowSize = alm.size();
    qDebug()<<"nRowSize:"<<nRowSize;
    if (0 == nRowSize)
        return;

//    QList<QVariant> lV1;
    int nColumnSize = alm.GetValue(0).size();
//    for (int i = 0; i < nColumnSize; ++i)
//    {
//        lV1.append(alm.GetValue(0).GetValue(i));
//    }

    TreeItem* pRow0 = new TreeItem(GetBranchRecord(alm.GetValue(0)), nullptr);

    for (int i = 1; i < nRowSize; ++i)
    {
//        QList<QVariant> lV2;
//        for (int k = 0; k < nColumnSize; ++k)
//        {
//            qDebug()<<"["<<i<<","<<k<<"]"<<alm.GetValue(i).GetValue(k);
//            lV2.append(alm.GetValue(i).GetValue(k));
//        }

        TreeItem* pRow1 = new TreeItem(GetBranchRecord(alm.GetValue(i)), pRow0);
        pRow0->appendChild(pRow1);
    }

    m_pRiskWatchGrid->AppendTreeData(pRow0);
    qDebug()<<"nColumnSize:"<<nColumnSize;
}

//LV1 正常，LV2追保，LV3相对强平，LV4绝对强平
void MainQuo::InitRiskWatchRoles()
{
    int nRole = Qt::UserRole + 1;
    m_pRiskWatchGrid->SetRole(nRole++, "branchID");
    m_pRiskWatchGrid->SetRole(nRole++, "branchName");
    m_pRiskWatchGrid->SetRole(nRole++, "LV3Count");
    m_pRiskWatchGrid->SetRole(nRole++, "LV3Percent");
    m_pRiskWatchGrid->SetRole(nRole++, "LV4Count");
    m_pRiskWatchGrid->SetRole(nRole++, "LV4Percent");
    m_pRiskWatchGrid->SetRole(nRole++, "LV2Count");
    m_pRiskWatchGrid->SetRole(nRole++, "LV2Percent");
    m_pRiskWatchGrid->SetRole(nRole++, "CallBalance");
    m_pRiskWatchGrid->SetRole(nRole++, "TotalPL");
    m_pRiskWatchGrid->SetRole(nRole++, "CustCount");
    qDebug()<<"InitRiskWatchRoles Size:"<<m_pRiskWatchGrid->roleNames().size();
}

QList<QVariant> MainQuo::GetBranchRecord( ArrayListMsg alm)
{
    int nNorNum = alm.GetQValue(7).toString().toInt();
    int nCallNum = alm.GetQValue(6).toString().toInt();
    int nForceNum = alm.GetQValue(4).toString().toInt();
    int nForceNumAbs = alm.GetQValue(5).toString().toInt();
    int nOutStock = alm.GetQValue(3).toString().toInt();
    int nNeg = alm.GetQValue(2).toString().toInt();
    int nTotal = nNorNum + nCallNum + nForceNum + nForceNumAbs + nOutStock + nNeg;
    QList<QVariant> lV2;    //与Roles对应
    lV2.append(alm.GetQValue(0));    //代理机构id
    lV2.append(alm.GetQValue(1));    //代理机构名称
    lV2.append(alm.GetQValue(4));    //相对强平客户数
    if (0 == nTotal)
    {
        lV2.append("0.00%");    //
        lV2.append(alm.GetQValue(5));    //相对强平客户数
        lV2.append("0.00%");    //
        lV2.append(alm.GetQValue(6));    //相对强平客户数
        lV2.append("0.00%");    //
    }
    else
    {
        lV2.append(QString::number(nForceNum*100.0/nTotal, 10, 2)+"%");    //
        lV2.append(alm.GetQValue(5));    //相对强平客户数
        lV2.append(QString::number(nForceNumAbs*100.0/nTotal, 10, 2)+"%");    //
        lV2.append(alm.GetQValue(6));    //相对强平客户数
        lV2.append(QString::number(nCallNum*100.0/nTotal, 10, 2)+"%");    //
    }
    lV2.append(QString("%L1").arg(alm.GetQValue(8).toString().toDouble(), 0 ,'f',2));    //追保金额
    lV2.append(QString("%L1").arg(alm.GetQValue(10).toString().toDouble(), 0 ,'f',2));    //总浮动盈亏
    lV2.append(QString::number(nTotal));    //
    return lV2;
}

